<template>
  <div class="query">
    <form-component
      ref="form"
      :configs="configs"
      :params="params"
      :is-query="isQuery"
      v-bind="$attrs"
      :default-form-item-width="formItemWidth"
    />
    <div class="query-btn">
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="submit"
      >查询</el-button>
      <el-button @click="reset">重置</el-button>
      <slot name="btn" />
    </div>
  </div>
</template>
<script>
import FormComponent from 'modules/component/template/Form'
import { on, off, throttle } from '@/utils'
export default {
  components: {
    FormComponent
  },
  props: {
    configs: {
      type: Array,
      default() {
        return []
      }
    },
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    isQuery: {
      type: Boolean,
      default: true
    },
    defaultFormItemWidth: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      responseItemWidth: '30%'
    }
  },
  computed: {
    formItemWidth() {
      return this.hasDefaultItemWidth
        ? this.defaultFormItemWidth
        : this.responseItemWidth
    },
    hasDefaultItemWidth() {
      return this.defaultFormItemWidth !== undefined
    }
  },
  mounted() {
    this.createReziseFn()
  },
  beforeDestroy() {
    this.removeResizeFn()
  },
  activated() {
    this.createReziseFn()
  },
  deactivated() {
    this.removeResizeFn()
  },
  methods: {
    submit() {
      const params = this.$refs.form.submit()
      this.$emit('query', params)
    },
    reset() {
      this.$refs.form.resetParams()
      this.$emit('reset')
    },
    setFormItemWidth() {
      const innerWidth = window.innerWidth
      if (innerWidth > 1000) {
        this.responseItemWidth = '33%'
      }
      if (innerWidth > 650 && innerWidth <= 1000) {
        this.responseItemWidth = '50%'
      }
      if (innerWidth <= 650) {
        this.responseItemWidth = '100%'
      }
    },
    createReziseFn() {
      if (this.throttleFunc && this.hasDefaultItemWidth) return
      this.setFormItemWidth()
      this.throttleFunc = throttle(500, false, this.setFormItemWidth)
      on(window, 'resize', this.throttleFunc)
    },
    removeResizeFn() {
      this.throttleFunc && off(window, 'resize', this.throttleFunc)
      this.throttleFunc = null
    }
  }
}
</script>
<style>
.query {
  margin: 20px 0;
}
.query-btn {
  padding-left: 100px;
  padding-bottom: 10px;
}
</style>
